import { exec } from 'child_process';
import { readFileSync, existsSync, createReadStream, PathLike } from 'fs';
import { parse } from 'yaml';
import FormData from 'form-data';
import axios from 'axios';
import { IOpenAPI } from 'qq-guild-bot';
import puppeteer, { Browser, BrowserFetcher } from 'puppeteer';
import { green, red, yellow } from 'kolorist';
// @ts-ignore
import { PUPPETEER_REVISIONS } from 'puppeteer-core/internal/revisions.js';
import { join } from 'path';
import ProgressBar from 'progress';
declare global {
  var client: IOpenAPI;
}

export function readYaml(url: string) {
  if (existsSync(url)) {
    const file = readFileSync(url, 'utf8');
    const data = parse(file);
    return data;
  } else {
    return `${url} 不存在`;
  }
}

export function exe(command: string) {
  return new Promise((resolve, reject) => {
    exec(command, (err, stdout, stderr) => {
      if (err) {
        console.error(err);
        process.exit();
      } else {
        resolve(stdout);
      }
    });
  });
}
// 发送本地图片
export async function sendImage(
  channelID: string,
  message: {
    file_image: PathLike;
    content?: string;
    msg_id: string;
  }
) {
  let url = '';
  if (client.config.sandbox) {
    url = 'https://sandbox.api.sgroup.qq.com';
  } else {
    url = 'https://api.sgroup.qq.com';
  }

  var picData = createReadStream(message.file_image);

  var formdata = new FormData();

  formdata.append('msg_id', message.msg_id);
  formdata.append('file_image', picData);
  if (typeof message.content === 'string') {
    formdata.append('content', message.content);
  }

  return axios({
    method: 'post',
    url: `${url}/channels/${channelID}/messages`,
    headers: {
      'Content-Type': formdata.getHeaders()['content-type'],
      'Authorization': `Bot ${client.config.appID}.${client.config.token}`
    },
    data: formdata
  });
}

let pic = 0;
let browser: boolean | Browser | void = false;
let chromePath: string = '';

let progressBar: ProgressBar = null;
let lastDownloadedBytes = 0;

function toMegabytes(bytes: number) {
  const mb = bytes / 1024 / 1024;
  return `${Math.round(mb * 10) / 10} Mb`;
}
// 下载进度条
function onProgress(downloadedBytes: number, totalBytes: any) {
  if (!progressBar) {
    progressBar = new ProgressBar(
      `Downloading chrome r${PUPPETEER_REVISIONS.chromium} - ${toMegabytes(
        totalBytes
      )} [:bar] :percent :etas `,
      {
        complete: '=',
        incomplete: ' ',
        width: 20,
        total: totalBytes
      }
    );
  }
  const delta = downloadedBytes - lastDownloadedBytes;
  lastDownloadedBytes = downloadedBytes;
  progressBar.tick(delta);
}

export function download() {
  return new Promise((resolve, reject) => {
    // 获取puppeteer安装路径
    if (chromePath === '') {
      const browserFetcher = new BrowserFetcher({
        path: join(process.cwd(), '.cache/puppeteer')
      });
      const revisionInfo = browserFetcher.revisionInfo(PUPPETEER_REVISIONS.chromium);
      // 判断是否下载
      if (revisionInfo.local) {
        chromePath = revisionInfo.executablePath;
        resolve('完成');
      } else {
        console.log(yellow('未检测到puppeteer,开始下载,请注意流量'));
        // 下载
        browserFetcher
          .download(PUPPETEER_REVISIONS.chromium, onProgress)
          .then(res => {
            // 获取路径
            chromePath = res.executablePath;
            console.log(green('下载完成'));
            resolve('下载完成');
          })
          .catch(err => {
            console.error(red('下载失败'));
            console.error(err);
            reject('失败');
          });
      }
    }
  });
}
/**
 * @description:
 * @param {PathLike} htmlPath html完整路径
 * @param {string} tab html tab标签
 * @param {string} imgPath 生成的图片完整路径
 * @return {Promise<boolean>}
 */
export async function getPu(htmlPath: PathLike, tab: string, imgPath: string) {
  if (pic === 0) {
    browser = false;
    console.info(green('puppeteer 启动中。。'));

    browser = await puppeteer
      .launch({
        executablePath: chromePath,
        headless: true,
        args: [
          '--disable-gpu',
          '--disable-dev-shm-usage',
          '--disable-setuid-sandbox',
          '--no-first-run',
          '--no-sandbox',
          '--no-zygote',
          '--single-process'
        ]
      })
      .catch(err => {
        console.error(red(err.toString()));
        if (String(err).includes('correct Chromium')) {
          console.error(
            red(
              '没有正确安装Chromium，可以尝试执行安装命令：node ./node_modules/puppeteer/install.js'
            )
          );
        }
        return false;
      });
    if (typeof browser === 'boolean' && !browser) {
      console.error(red('puppeteer 启动失败'));
      return false;
    }
    console.info(green('puppeteer 启动成功'));
  }

  const page = await (browser as Browser).newPage();
  await page.goto(`file://${htmlPath}`);
  let body = await page.$(tab);
  await body.screenshot({
    path: imgPath
  });

  pic++;
  // 大于等于30次重开
  if (pic >= 30) {
    (browser as Browser).close().catch(err => console.error(red(err.toString())));
    console.info(green('puppeteer 关闭成功'));
    pic = 0;
  }

  return true;
}
